﻿using BootstrapBlazor.Components;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Forms;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace CyssBlazor.Shared.Components
{
    public class BaseValidateComponent<TValue> : BaseComponent
    {
        private TValue _value;

        [Parameter]
        public TValue Value
        {
            get => _value;
            set
            {
                if (_value == null)
                {
                    if (value == null) return;
                }
                else
                {
                    if (_value.Equals(value)) return;
                }
                _value = value;
                ValueChanged.InvokeAsync(value);
            }
        }
        [Parameter]
        public EventCallback<TValue> ValueChanged { get; set; }

        /// <summary>
        /// Gets or sets an expression that identifies the bound value.
        /// </summary>
        [Parameter]
        public Expression<Func<TValue>>? ValueExpression { get; set; }

        [Parameter]
        public string? DisplayText { get; set; }


        [Parameter]
        public bool ShowLabel { set; get; } = true;

        protected FieldIdentifier? fieldIdentifier { set; get; }

        [CascadingParameter]
        protected EditContext? editContext { set; get; }


        protected bool? IsValid { set; get; }

        protected string? ValidCss => IsValid.HasValue ? (IsValid.Value ? "is-valid" : "is-invalid") : null;

        protected override void OnInitialized()
        {
            if (ValueExpression != null)
            {
                fieldIdentifier = Microsoft.AspNetCore.Components.Forms.FieldIdentifier.Create<TValue>(ValueExpression);
                if (ShowLabel && string.IsNullOrWhiteSpace(DisplayText) && fieldIdentifier.HasValue)
                {
                    DisplayText = fieldIdentifier.Value.GetDisplayName();
                }
            }
            if (editContext != null && fieldIdentifier != null)
            {
                editContext.OnValidationStateChanged += EditContext_OnValidationStateChanged;
            }
            base.OnInitialized();
        }

        public override void Dispose()
        {
            if (editContext != null) editContext.OnValidationStateChanged -= EditContext_OnValidationStateChanged;
            base.Dispose();
        }

        private void EditContext_OnValidationStateChanged(object? sender, ValidationStateChangedEventArgs e)
        {
            if (editContext != null && fieldIdentifier != null)
            {
                if (editContext.GetValidationMessages(fieldIdentifier.Value).Any())
                {
                    IsValid = false;
                }
                else
                {
                    IsValid = true;
                }
            }

        }


    }
}
